import time
from functools import wraps
from typing import Tuple, Optional, Any
import re
from flask import request, jsonify, current_app
import logging
from threading import Lock
import hashlib
import json

logger = logging.getLogger(__name__)

class RateLimiter:
    """速率限制器"""
    def __init__(self):
        self._locks = {}
        self._request_records = {}

    def _get_lock(self, key: str):
        if key not in self._locks:
            self._locks[key] = Lock()
        return self._locks[key]

    def _clean_old_records(self, key: str, window: int):
        now = time.time()
        self._request_records[key] = [
            ts for ts in self._request_records.get(key, [])
            if now - ts < window
        ]

    def check_rate_limit(self, key: str, max_requests: int, window: int) -> bool:
        with self._get_lock(key):
            self._clean_old_records(key, window)
            if len(self._request_records.get(key, [])) >= max_requests:
                return False
            now = time.time()
            if key not in self._request_records:
                self._request_records[key] = []
            self._request_records[key].append(now)
            return True

rate_limiter = RateLimiter()

def rate_limit(max_requests: int = 60, window: int = 60):
    def decorator(f):
        @wraps(f)
        def decorated_function(*args, **kwargs):
            client_id = request.remote_addr
            if not rate_limiter.check_rate_limit(client_id, max_requests, window):
                return jsonify({
                    'error': 'Rate limit exceeded',
                    'message': f'请求过于频繁，请在{window}秒后重试'
                }), 429
            return f(*args, **kwargs)
        return decorated_function
    return decorator

def sanitize_input(content: str) -> str:
    content = re.sub(r'<[^>]*>', '', content)
    content = ' '.join(content.split())
    return content.strip()

def validate_input(content: Any) -> Tuple[bool, Optional[str]]:
    if not isinstance(content, str):
        return False, "输入必须是字符串类型"
    content = sanitize_input(content)
    if not content:
        return False, "输入不能为空"
    max_length = current_app.config.get('MAX_MESSAGE_LENGTH', 2000)
    if len(content) > max_length:
        return False, f"输入长度不能超过{max_length}字符"
    return True, None

def generate_conversation_title(content: str, max_length: int = 50) -> str:
    title = content.strip().split('\n', 1)[0]
    title = re.sub(r'\s+', ' ', title).strip()
    if len(title) > max_length:
        title = title[:max_length].strip() + '...'
    return title

class APIError(Exception):
    def __init__(self, message: str, status_code: int = 400):
        super().__init__(message)
        self.message = message
        self.status_code = status_code
